/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 * <p>
 * https://www.renren.io
 * <p>
 * 版权所有，侵权必究！
 */

package yancy.modules.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import yancy.common.utils.PageUtils;
import yancy.common.utils.Query;
import yancy.modules.sys.dao.SysAuthorDao;
import yancy.modules.sys.entity.SysAuthor;
import yancy.modules.sys.service.SysAuthorService;
import yancy.modules.sys.service.SysRoleService;
import yancy.modules.sys.service.SysUserRoleService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;


/**
 * 系统用户
 *
 * @author Mark sunlightcs@gmail.com
 */
@Service("sysAuthorService")
@Slf4j
public class SysAuthorServiceImpl extends ServiceImpl<SysAuthorDao, SysAuthor>
        implements SysAuthorService {
    @Autowired
    private SysUserRoleService sysUserRoleService;
    @Autowired
    private SysRoleService sysRoleService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String username = (String) params.get("username");
        Long createUserId = (Long) params.get("createUserId");

        IPage<SysAuthor> page = this.page(
                new Query<SysAuthor>().getPage(params),
                new QueryWrapper<SysAuthor>()
                        .like(StringUtils.isNotBlank(username), "username", username)
                        .eq(createUserId != null, "create_user_id", createUserId)
        );

        return new PageUtils(page);
    }


    private boolean canDeleted(Long authorId) {
        Integer ref = baseMapper.hasReference(authorId);
        return ref == null || ref == 0;
    }

    @Override
    public boolean deleteById(Long authorId) {
        if (!canDeleted(authorId)) {
            return false;
        }
        log.info("authorId {} was deleted", authorId);
        baseMapper.deleteById(authorId);
        return true;
    }
}
